import Vue from 'vue';
import iview from 'view-design';
import Router from 'vue-router';

Vue.use(Router);

let defaultRouters = [
  {
    path: '404',
    component: () => import('~/components/pages/404.vue'),
    meta: {
      requireAuth: false,
      title: '页面未找到',
    },
  },
  {
    path: '*',
    redirect: '/404',
  },
];

export default {
  init (routes, title) {
    if (routes) {
      routes.forEach(item => {
        if (item.children) {
          item.children.push(...defaultRouters);
        }
      });
    }

    var router = new Router({
      // mode: 'history',
      routes: [...routes],
    });

    /**
     * 页面路由跳转前的拦截处理。
     */
    router.beforeResolve((to, from, next) => {
      const store = router.app.$store;

      iview.LoadingBar.start();

      router.app.renderCrumbs();

      if (to.meta) {
        if (to.meta.requireAuth) {
          if (!store.getters.isLogged()) {
            router.push('/logOn');
          }
        }

        if (to.meta.title) {
          const subTitle = to.meta.title ? to.meta.title : to.matched.length > 1 ? to.matched[0].meta.title : '';

          document.title = `${title || '部署和服务监控系统'} - ${subTitle}`;
        }
      }

      next();
    });

    /**
     * 页面路由跳转完成后的处理。
     */
    router.afterEach(transition => {
      iview.LoadingBar.finish();

      router.app.$nextTick(() => {
        router.app.resetSize();
      });
    });

    return router;
  },
};
